#include "task_service.h"

#include <QString>
#include <QObject>
#include <QByteArray>
#include <optional>

#include "subtasks/charge_task.h"
#include "subtasks/jack_task.h"
#include "subtasks/move_task.h"
#include "subtasks/park_task.h"
#include "application/map/caller/caller_manager.h"
#include "application/map/caller/caller_protocol.h"

namespace application {
namespace task {

TaskService::TaskService(
    std::shared_ptr<vehicle::VehicleService> vehicleService,
    std::shared_ptr<dispatcher::DispatcherService> dispatcherService,
    std::shared_ptr<MapApplicationService> mapService,
    std::shared_ptr<infrastructure::services::CommonService> commonService)
    : m_vehicleService(vehicleService),
      m_dispatcherService(dispatcherService),
      m_mapService(mapService),
      m_callerManager(mapService ? mapService->getCallerManager(mapService->getCurrentFloor())
                                 : std::shared_ptr<caller::CallerManager>()),
      m_logger(commonService ? commonService->getLogger("TaskService")
                             : nullptr),
      m_executor(std::make_unique<TaskExecutor>(m_logger,
                                                m_vehicleService,
                                                m_dispatcherService,
                                                m_mapService)) {
  if (m_dispatcherService) {
    m_dispatcherService->setSolveFailureCallback(
        [this](const QString& message) {
          if (m_planningFailureNotifier) {
            m_planningFailureNotifier(message);
          }
        });
  }
  // 创建任务配置提供者
  m_configProvider =
      std::make_shared<infrastructure::configuration::TaskConfigProvider>(
          "config/taskconf.json", m_logger);

  // 创建任务模板工厂
  m_templateFactory = std::make_unique<TaskTemplateFactory>(
      m_vehicleService, m_dispatcherService, m_mapService, m_logger);

  // 加载任务配置
  auto loadResult = m_configProvider->loadConfig();
  if (!loadResult.isSuccess()) {
    if (m_logger) {
      m_logger->warning(QString("Failed to load task config: %1")
                            .arg(loadResult.getErrorMessage()));
    }
  }

  if (m_logger) {
    m_logger->info("TaskService initialized");
  }

  if (m_vehicleService) {
    m_autoChargeConnection = QObject::connect(
        m_vehicleService.get(),
        &vehicle::VehicleService::autoChargeRequested,
        m_vehicleService.get(),
        [this](int agvNumber,
               vehicle::VehicleService::AutoChargeReason reason,
               int batteryLevel) {
          this->handleAutoChargeRequest(agvNumber, reason, batteryLevel);
        });
  }
}

TaskService::~TaskService()
{
  if (m_autoChargeConnection) {
    QObject::disconnect(m_autoChargeConnection);
  }
}

// ==================== 任务创建 ====================

kernel::Result<std::string> TaskService::createTaskFromTemplate(
    const std::string& templateName, int preferredAgvNumber, bool fromCaller) {
  if (m_logger) {
    m_logger->info(QString("Creating task from template: %1, preferredAgv: %2, fromCaller: %3")
                       .arg(QString::fromStdString(templateName))
                       .arg(preferredAgvNumber)
                       .arg(fromCaller ? "true" : "false"));
  }

  // 1. 获取任务模板
  auto templateResult = m_configProvider->getTemplate(templateName);
  if (!templateResult.isSuccess()) {
    return kernel::Result<std::string>::failure(
        templateResult.getErrorCode(), templateResult.getErrorMessage());
  }

  const auto& templateConfig = templateResult.getValue();

  auto cooldownCheck = ensureTemplateCooldown(templateConfig.name);
  if (!cooldownCheck.isSuccess()) {
    return kernel::Result<std::string>::failure(
        cooldownCheck.getErrorCode(), cooldownCheck.getErrorMessage());
  }

  // 连发检查：仅当来自呼叫器且启用了连发检查时执行
  const bool shouldCheckDuplicate = fromCaller && m_callerDuplicateCheckEnabled;
  if (shouldCheckDuplicate && m_executor->hasActiveTaskByName(templateConfig.name)) {
    QString err = QStringLiteral("任务 %1 正在执行，无法重复创建")
                      .arg(QString::fromStdString(templateConfig.name));
    if (m_logger) {
      m_logger->warning(err);
    }
    return kernel::Result<std::string>::failure(
        kernel::ErrorCode::InvalidOperation, err);
  }

  // 对发检查：仅当来自呼叫器且启用了对发检查时执行
  const bool shouldCheckMutex = fromCaller && m_callerMutexCheckEnabled;
  if (shouldCheckMutex && !templateConfig.mutexTask.empty()) {
    if (m_executor->hasActiveTaskByName(templateConfig.mutexTask)) {
      QString err = QStringLiteral("任务 %1 与互斥任务 %2 同时存在，无法创建")
                        .arg(QString::fromStdString(templateConfig.name))
                        .arg(QString::fromStdString(templateConfig.mutexTask));
      if (m_logger) {
        m_logger->warning(err);
      }
      return kernel::Result<std::string>::failure(
          kernel::ErrorCode::InvalidOperation, err);
    }
  }

  // 2. 选择AGV（如果未指定）
  int selectedAgv = preferredAgvNumber;
  if (selectedAgv == -1) {
    auto resolvePrimaryMoveTarget =
        [&templateConfig]() -> std::optional<std::pair<int, std::string>> {
      for (const auto& subTask : templateConfig.subTasks) {
        if (subTask.type == kernel::task::SubTaskType::Move &&
            !subTask.stationName.empty()) {
          return std::make_pair(subTask.floor, subTask.stationName);
        }
      }
      return std::nullopt;
    };

    auto moveTarget = resolvePrimaryMoveTarget();
    if (!moveTarget) {
      return kernel::Result<std::string>::failure(
          kernel::ErrorCode::InvalidConfiguration,
          QStringLiteral("Template lacks move task for automatic AGV selection"));
    }

    selectedAgv = m_dispatcherService->selectBestIdleAgv(
        moveTarget->second, moveTarget->first, templateConfig.allowedAgvTypes);
    if (selectedAgv == -1) {
      QString errorMsg = QStringLiteral("No idle AGV available");
      if (!templateConfig.allowedAgvTypes.empty()) {
        errorMsg += QStringLiteral(" matching type requirements for task '") +
                    QString::fromStdString(templateName) + QStringLiteral("'");
      }
      return kernel::Result<std::string>::failure(
          kernel::ErrorCode::NotFound, errorMsg);
    }

    if (m_logger) {
      m_logger->debug(QString("Template %1 auto-selected AGV %2 via dispatcher "
                              "(station=%3, floor=%4)")
                          .arg(QString::fromStdString(templateName))
                          .arg(selectedAgv)
                          .arg(QString::fromStdString(moveTarget->second))
                          .arg(moveTarget->first));
    }
  } else {
    // 手动指定车辆时,需要校验车型是否符合要求
    if (!templateConfig.allowedAgvTypes.empty()) {
      auto agv = m_vehicleService->getVehicle(selectedAgv);
      if (!agv) {
        return kernel::Result<std::string>::failure(
            kernel::ErrorCode::InvalidOperation,
            QString("Vehicle %1 not found").arg(selectedAgv));
      }

      bool typeAllowed = false;
      for (const auto& allowedType : templateConfig.allowedAgvTypes) {
        if (agv->getType() == allowedType) {
          typeAllowed = true;
          break;
        }
      }

      if (!typeAllowed) {
        QString allowedTypesStr;
        for (size_t i = 0; i < templateConfig.allowedAgvTypes.size(); ++i) {
          if (i > 0) allowedTypesStr += ", ";
          allowedTypesStr += QString::fromStdString(
              kernel::agv::agvTypeToString(templateConfig.allowedAgvTypes[i]));
        }

        if (m_logger) {
          m_logger->warning(QString("Vehicle %1 type %2 not allowed for task '%3' (allowed: %4)")
                                .arg(selectedAgv)
                                .arg(QString::fromStdString(kernel::agv::agvTypeToString(agv->getType())))
                                .arg(QString::fromStdString(templateName))
                                .arg(allowedTypesStr));
        }

        return kernel::Result<std::string>::failure(
            kernel::ErrorCode::InvalidOperation,
            QString("Vehicle %1 type %2 is not allowed for task '%3' (allowed types: %4)")
                .arg(selectedAgv)
                .arg(QString::fromStdString(kernel::agv::agvTypeToString(agv->getType())))
                .arg(QString::fromStdString(templateName))
                .arg(allowedTypesStr));
      }
    }
  }

  auto availability = ensureAgvAvailableForTask(selectedAgv);
  if (!availability.isSuccess()) {
    return kernel::Result<std::string>::failure(
        availability.getErrorCode(), availability.getErrorMessage());
  }

  // 3. 使用工厂创建子任务列表
  auto subTasks =
      m_templateFactory->createSubTasks(templateConfig, selectedAgv);
  if (subTasks.empty()) {
    return kernel::Result<std::string>::failure(
        kernel::ErrorCode::BusinessError,
        QStringLiteral("Failed to create subtasks from template"));
  }

  // 4. 添加到执行器
  std::string chainId =
      m_executor->addTaskChain(selectedAgv, std::move(subTasks),
                               templateName  // 传递任务模板名称作为任务名称
      );

  if (m_logger) {
    m_logger->info(QString("Task created from template: %1, chainId=%2, agv=%3")
                       .arg(QString::fromStdString(templateName))
                       .arg(QString::fromStdString(chainId))
                       .arg(selectedAgv));
  }
  recordTemplateTrigger(templateConfig.name);
  return kernel::Result<std::string>::success(chainId);
}

std::vector<std::string> TaskService::getAvailableTemplates() const {
  return m_configProvider->getTemplateNames();
}

kernel::Result<void> TaskService::reloadTaskConfig() {
  auto result = m_configProvider->reloadConfig();
  if (result.isSuccess()) {
    if (m_logger) {
      m_logger->info("Task config reloaded successfully");
    }
    return kernel::Result<void>::success();
  } else {
    return kernel::Result<void>::failure(result.getErrorCode(),
                                         result.getErrorMessage());
  }
}

kernel::Result<std::string> TaskService::createMoveTask(
    const std::string& targetStation, int floor, int preferredAgvNumber) {
  if (m_logger) {
    m_logger->info(QString("Creating move task to station: %1, floor: %2")
                       .arg(QString::fromStdString(targetStation))
                       .arg(floor));
  }

  // 1. 验证AGV（必须指定AGV）
  if (preferredAgvNumber == -1) {
    return kernel::Result<std::string>::failure(
        kernel::ErrorCode::InvalidArgument,
        QStringLiteral("AGV number must be specified for move task"));
  }

  auto* agv = m_vehicleService->getVehicle(preferredAgvNumber);
  if (!agv) {
    return kernel::Result<std::string>::failure(
        kernel::ErrorCode::NotFound,
        QString("AGV not found: %1").arg(preferredAgvNumber));
  }

  auto availability = ensureAgvAvailableForTask(preferredAgvNumber);
  if (!availability.isSuccess()) {
    return kernel::Result<std::string>::failure(
        availability.getErrorCode(), availability.getErrorMessage());
  }

  // 2. 创建移动任务链（MoveTask内部会处理站点请求、路径规划等）
  std::vector<std::unique_ptr<SubTaskBase>> tasks;
  tasks.push_back(std::make_unique<MoveTask>(
      targetStation, floor, m_vehicleService, m_dispatcherService,
      m_mapService, m_logger));

  // 3. 添加到执行器
  std::string chainId =
      m_executor->addTaskChain(preferredAgvNumber, std::move(tasks));

  if (m_logger) {
    m_logger->info(QString("Move task created: chainId=%1, agv=%2")
                       .arg(QString::fromStdString(chainId))
                       .arg(preferredAgvNumber));
  }

  return kernel::Result<std::string>::success(chainId);
}

kernel::Result<std::string> TaskService::createChargeTask(
    int agvNumber, const std::string& chargePoint, int targetBatteryLevel) {
  if (m_logger) {
    m_logger->info(
        QString("Creating charge task: agv=%1, chargePoint=%2, target=%3%")
            .arg(agvNumber)
            .arg(QString::fromStdString(chargePoint))
            .arg(targetBatteryLevel));
  }

  // 1. 验证AGV（必须指定AGV）
  if (agvNumber == -1) {
    return kernel::Result<std::string>::failure(
        kernel::ErrorCode::InvalidArgument,
        QStringLiteral("AGV number must be specified for charge task"));
  }

  auto* agv = m_vehicleService->getVehicle(agvNumber);
  if (!agv) {
    return kernel::Result<std::string>::failure(
        kernel::ErrorCode::NotFound,
        QString("AGV not found: %1").arg(agvNumber));
  }

  auto availability = ensureAgvAvailableForTask(agvNumber);
  if (!availability.isSuccess()) {
    return kernel::Result<std::string>::failure(
        availability.getErrorCode(), availability.getErrorMessage());
  }

  // 2. 创建任务链：由 ChargeTask 在运行时申请/占用充电点
  std::vector<std::unique_ptr<SubTaskBase>> tasks;
  tasks.push_back(std::make_unique<ChargeTask>(
      m_vehicleService, m_mapService, m_dispatcherService, m_logger, chargePoint,
      targetBatteryLevel));

  // 3. 添加到执行器
  std::string chainId = m_executor->addTaskChain(
      agvNumber, std::move(tasks), QStringLiteral("充电").toStdString());

  if (chainId.empty()) {
    if (m_logger) {
      m_logger->error(QString("Failed to add charge task chain for AGV %1")
                          .arg(agvNumber));
    }
    return kernel::Result<std::string>::failure(
        kernel::ErrorCode::BusinessError, QStringLiteral("无法创建充电任务链"));
  }

  if (m_logger) {
    m_logger->info(QString("Charge task created: chainId=%1, agv=%2")
                       .arg(QString::fromStdString(chainId))
                       .arg(agvNumber));
  }

  return kernel::Result<std::string>::success(chainId);
}

kernel::Result<std::string> TaskService::createParkTask(
    int agvNumber, const std::string& parkingStation) {
  if (m_logger) {
    m_logger->info(QString("Creating park task: agv=%1, station=%2")
                       .arg(agvNumber)
                       .arg(QString::fromStdString(parkingStation)));
  }

  // 1. 验证AGV（必须指定AGV）
  if (agvNumber == -1) {
    return kernel::Result<std::string>::failure(
        kernel::ErrorCode::InvalidArgument,
        QStringLiteral("AGV number must be specified for park task"));
  }

  auto* agv = m_vehicleService->getVehicle(agvNumber);
  if (!agv) {
    return kernel::Result<std::string>::failure(
        kernel::ErrorCode::NotFound,
        QString("AGV not found: %1").arg(agvNumber));
  }

  // 2. 创建任务链：停车任务（ParkTask内部会处理站点申请、移动等）
  std::vector<std::unique_ptr<SubTaskBase>> tasks;

  // 停车任务（空字符串表示自动申请停车点，-1表示使用当前楼层）
  tasks.push_back(std::make_unique<ParkTask>(
      m_vehicleService, m_mapService, m_dispatcherService, m_logger,
      parkingStation, -1));

  // 3. 添加到执行器
  std::string chainId = m_executor->addTaskChain(
      agvNumber, std::move(tasks), QStringLiteral("停车").toStdString());

  if (m_logger) {
    m_logger->info(QString("Park task created: chainId=%1, agv=%2")
                       .arg(QString::fromStdString(chainId))
                       .arg(agvNumber));
  }

  return kernel::Result<std::string>::success(chainId);
}

kernel::Result<std::string> TaskService::createTransportTask(
    const std::string& pickStation, const std::string& dropStation, int floor,
    int preferredAgvNumber) {
  if (m_logger) {
    m_logger->info(
        QString("Creating transport task: pick=%1, drop=%2, floor=%3")
            .arg(QString::fromStdString(pickStation))
            .arg(QString::fromStdString(dropStation))
            .arg(floor));
  }
  // 1. 验证AGV（必须指定AGV）
  if (preferredAgvNumber == -1) {
    return kernel::Result<std::string>::failure(
        kernel::ErrorCode::InvalidArgument,
        QStringLiteral("AGV number must be specified for charge task"));
  }

  auto availability = ensureAgvAvailableForTask(preferredAgvNumber);
  if (!availability.isSuccess()) {
    return kernel::Result<std::string>::failure(
        availability.getErrorCode(), availability.getErrorMessage());
  }
  // 2. 创建任务链：移动到取货点 -> 顶升上升 -> 移动到送货点 -> 顶升下降
  std::vector<std::unique_ptr<SubTaskBase>> tasks;

  // 2.1 移动到取货点
  tasks.push_back(std::make_unique<MoveTask>(
      pickStation, floor, m_vehicleService, m_dispatcherService, m_mapService,
      m_logger));

  // 2.2 顶升上升（取货）
  tasks.push_back(std::make_unique<JackTask>(true,  // raise
                                             m_vehicleService, m_logger,
                                             pickStation,
                                             6  // 等待6秒
                                             ));

  // 2.4 移动到送货点
  tasks.push_back(std::make_unique<MoveTask>(
      dropStation, floor, m_vehicleService, m_dispatcherService, m_mapService,
      m_logger));

  // 2.5 顶升下降（卸货）
  tasks.push_back(std::make_unique<JackTask>(false,  // lower
                                             m_vehicleService, m_logger,
                                             dropStation,
                                             6  // 等待6秒
                                             ));

  // 3. 添加到执行器
  std::string chainId =
      m_executor->addTaskChain(preferredAgvNumber, std::move(tasks));

  if (m_logger) {
    m_logger->info(QString("Transport task created: chainId=%1, agv=%2")
                       .arg(QString::fromStdString(chainId))
                       .arg(preferredAgvNumber));
  }

  return kernel::Result<std::string>::success(chainId);
}

// ==================== 任务控制 ====================

kernel::Result<void> TaskService::pauseTask(const std::string& chainId) {
  bool success = m_executor->pauseTaskChain(chainId);
  if (success) {
    if (m_logger) {
      m_logger->info(
          QString("Task paused: %1").arg(QString::fromStdString(chainId)));
    }
    return kernel::Result<void>::success();
  } else {
    return kernel::Result<void>::failure(
        kernel::ErrorCode::NotFound, QString("Task chain not found: %1")
                                         .arg(QString::fromStdString(chainId)));
  }
}

kernel::Result<void> TaskService::resumeTask(const std::string& chainId) {
  bool success = m_executor->resumeTaskChain(chainId);
  if (success) {
    if (m_logger) {
      m_logger->info(
          QString("Task resumed: %1").arg(QString::fromStdString(chainId)));
    }
    return kernel::Result<void>::success();
  } else {
    return kernel::Result<void>::failure(
        kernel::ErrorCode::NotFound, QString("Task chain not found: %1")
                                         .arg(QString::fromStdString(chainId)));
  }
}

kernel::Result<void> TaskService::cancelTask(const std::string& chainId) {
  bool success = m_executor->cancelTaskChain(chainId);
  if (success) {
    if (m_logger) {
      m_logger->info(
          QString("Task cancelled: %1").arg(QString::fromStdString(chainId)));
    }
    return kernel::Result<void>::success();
  } else {
    return kernel::Result<void>::failure(
        kernel::ErrorCode::NotFound, QString("Task chain not found: %1")
                                         .arg(QString::fromStdString(chainId)));
  }
}

kernel::Result<void> TaskService::resetCurrentSubTask(
    const std::string& chainId) {
  bool success = m_executor->resetCurrentSubTask(chainId);
  if (success) {
    if (m_logger) {
      m_logger->info(QString("Subtask reset to Init: %1")
                         .arg(QString::fromStdString(chainId)));
    }
    return kernel::Result<void>::success();
  }

  return kernel::Result<void>::failure(
      kernel::ErrorCode::NotFound,
      QString("Task chain not found or no active subtask: %1")
          .arg(QString::fromStdString(chainId)));
}

bool TaskService::rescheduleAgvTask(int agvNumber)
{
  if (!m_dispatcherService) {
    if (m_logger) {
      m_logger->warning("DispatcherService unavailable for reschedule request");
    }
    return false;
  }

  if (agvNumber < 0) {
    if (m_logger) {
      m_logger->warning(QString("Invalid AGV number for reschedule: %1").arg(agvNumber));
    }
    return false;
  }

  bool accepted = m_dispatcherService->rescheduleAgvTask(agvNumber);
  if (m_logger) {
    if (accepted) {
      m_logger->info(QString("Reschedule request accepted for AGV %1").arg(agvNumber));
    } else {
      m_logger->warning(QString("Reschedule request rejected for AGV %1").arg(agvNumber));
    }
  }
  return accepted;
}

// ==================== 任务查询 ====================

std::vector<std::string> TaskService::getActiveTaskIds() const {
  return m_executor->getActiveChainIds();
}

std::vector<std::string> TaskService::getTaskIdsByAgv(int agvNumber) const {
  return m_executor->getChainIdsByAgv(agvNumber);
}

const TaskChainState* TaskService::getTaskState(
    const std::string& chainId) const {
  return m_executor->getTaskChainState(chainId);
}

// ==================== 服务控制 ====================

void TaskService::start() {
  m_executor->start();
  if (m_logger) {
    m_logger->info("TaskService started");
  }
}

void TaskService::stop() {
  m_executor->stop();
  if (m_logger) {
    m_logger->info("TaskService stopped");
  }
}

// ==================== 私有辅助方法 ====================

int TaskService::selectLowBatteryAgv(int floor, int batteryThreshold) {
  auto idleAgvs = m_dispatcherService->getIdleAgvs(floor);

  int selectedAgv = -1;
  int lowestBattery = 100;

  for (int agvNumber : idleAgvs) {
    auto* agv = m_vehicleService->getVehicle(agvNumber);
    if (!agv) {
      continue;
    }

    int battery = agv->getBatteryLevel();
    if (battery < batteryThreshold && battery < lowestBattery) {
      lowestBattery = battery;
      selectedAgv = agvNumber;
    }
  }

  if (m_logger && selectedAgv != -1) {
    m_logger->debug(QString("Selected low battery AGV: %1 (battery: %2%)")
                        .arg(selectedAgv)
                        .arg(lowestBattery));
  }

  return selectedAgv;
}

kernel::Result<void> TaskService::ensureAgvAvailableForTask(int agvNumber) const
{
  if (agvNumber == -1 || !m_executor) {
    return kernel::Result<void>::success();
  }

  if (!m_executor->hasActiveChainForAgv(agvNumber)) {
    return kernel::Result<void>::success();
  }

  QString error =
      QStringLiteral("AGV %1 已有未完成任务，无法创建新的任务链").arg(agvNumber);
  if (m_logger) {
    m_logger->warning(error);
  }
  return kernel::Result<void>::failure(kernel::ErrorCode::InvalidOperation, error);
}

kernel::Result<void> TaskService::ensureTemplateCooldown(const std::string& templateName) const
{
  if (templateName.empty()) {
    return kernel::Result<void>::success();
  }
  if (m_taskCooldown.count() <= 0) {
    return kernel::Result<void>::success();
  }
  auto it = m_lastTemplateTriggers.find(templateName);
  if (it == m_lastTemplateTriggers.end()) {
    return kernel::Result<void>::success();
  }
  auto now = std::chrono::system_clock::now();
  auto elapsed = now - it->second;
  if (elapsed >= m_taskCooldown) {
    return kernel::Result<void>::success();
  }
  auto remaining = std::chrono::duration_cast<std::chrono::seconds>(
      m_taskCooldown - elapsed);
  QString err = QStringLiteral("任务 %1 触发过于频繁，请在 %2 秒后重试")
                    .arg(QString::fromStdString(templateName))
                    .arg(remaining.count());
  if (m_logger) {
    m_logger->warning(err);
  }
  return kernel::Result<void>::failure(kernel::ErrorCode::InvalidOperation, err);
}

void TaskService::recordTemplateTrigger(const std::string& templateName)
{
  if (templateName.empty()) {
    return;
  }
  m_lastTemplateTriggers[templateName] = std::chrono::system_clock::now();
}

void TaskService::handleAutoChargeRequest(
    int agvNumber,
    vehicle::VehicleService::AutoChargeReason reason,
    int batteryLevel)
{
  const int targetBatteryLevel =
      reason == vehicle::VehicleService::AutoChargeReason::IdleCharge ? 90 : 100;

  auto result = createChargeTask(agvNumber, "", targetBatteryLevel);
  if (!result.isSuccess()) {
    if (m_logger) {
      m_logger->warning(QString("自动充电任务创建失败: agv=%1, reason=%2, error=%3")
                            .arg(agvNumber)
                            .arg(reason == vehicle::VehicleService::AutoChargeReason::IdleCharge
                                     ? QStringLiteral("IdleCharge")
                                     : QStringLiteral("LowBattery"))
                            .arg(result.getErrorMessage()));
    }
    return;
  }

  // 充电任务创建成功，重置自动充电定时器，避免立即再次触发
  if (m_vehicleService) {
    m_vehicleService->resetAutoChargeTimer(agvNumber);
  }

  if (m_logger) {
    m_logger->info(QString("自动创建充电任务: agv=%1, reason=%2, battery=%3%, chainId=%4")
                       .arg(agvNumber)
                       .arg(reason == vehicle::VehicleService::AutoChargeReason::IdleCharge
                                ? QStringLiteral("IdleCharge")
                                : QStringLiteral("LowBattery"))
                       .arg(batteryLevel)
                       .arg(QString::fromStdString(result.getValue())));
  }
}

// ==================== 呼叫器触发任务 ====================

void TaskService::setCallerTriggerEnabled(bool enabled) {
  m_callerTriggerEnabled = enabled;
  if (m_logger) {
    m_logger->info(QString("呼叫器触发任务%1").arg(enabled ? "已启用" : "已禁用（维护模式）"));
  }
}

bool TaskService::isCallerTriggerEnabled() const {
  return m_callerTriggerEnabled;
}

void TaskService::setCallerDuplicateCheckEnabled(bool enabled) {
  m_callerDuplicateCheckEnabled = enabled;
  if (m_logger) {
    m_logger->info(QString("呼叫器连发检查%1").arg(enabled ? "已启用" : "已禁用"));
  }
}

bool TaskService::isCallerDuplicateCheckEnabled() const {
  return m_callerDuplicateCheckEnabled;
}

void TaskService::setCallerMutexCheckEnabled(bool enabled) {
  m_callerMutexCheckEnabled = enabled;
  if (m_logger) {
    m_logger->info(QString("呼叫器对发检查%1").arg(enabled ? "已启用" : "已禁用"));
  }
}

bool TaskService::isCallerMutexCheckEnabled() const {
  return m_callerMutexCheckEnabled;
}

void TaskService::handleCallerTriggeredTask(const caller::CallerMessage& msg) {
  // 检查维护模式
  if (!m_callerTriggerEnabled) {
    if (m_logger) {
      m_logger->warning(QString("呼叫器触发已禁用（维护模式），跳过任务: %1").arg(msg.taskName));
    }
    return;
  }

  if (m_logger) {
    m_logger->info(QString("呼叫器触发任务: %1").arg(msg.taskName));
  }

  // 尝试创建任务（fromCaller=true，应用呼叫器专属的连发/对发检查）
  auto result = createTaskFromTemplate(msg.taskName.toStdString(), -1, true);

  if (!result.isSuccess()) {
    // 任务创建失败
    if (m_logger) {
      m_logger->warning(QString("呼叫器触发任务失败: taskName=%1, error=%2")
                            .arg(msg.taskName)
                            .arg(result.getErrorMessage()));
    }

    if (auto manager = m_callerManager.lock()) {
      manager->sendTaskResult(msg, false);
    }
  } else {
    // 任务创建成功
    if (m_logger) {
      m_logger->info(QString("呼叫器触发任务成功: taskName=%1, chainId=%2")
                         .arg(msg.taskName)
                         .arg(QString::fromStdString(result.getValue())));
    }

    if (auto manager = m_callerManager.lock()) {
      manager->sendTaskResult(msg, true);
    }
  }
}

}  // namespace task
}  // namespace application

